package com.bawei.demo_shoppingcar.fragment;


import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.demo_shoppingcar.R;
import com.bawei.demo_shoppingcar.activity.AD5WebViewActivity;
import com.bawei.demo_shoppingcar.activity.CommodityActivity;
import com.bawei.demo_shoppingcar.adapter.MyRecyclerAdapterTop;
import com.bawei.demo_shoppingcar.application.ContentData;
import com.bawei.demo_shoppingcar.bean.CommdityBean;
import com.bawei.demo_shoppingcar.bean.ShoppingDataBean;
import com.bawei.demo_shoppingcar.interfac.UpdateShopping;
import com.bawei.demo_shoppingcar.utils.GlideImageLoader;
import com.bawei.demo_shoppingcar.utils.HomeAsyncTask;
import com.bawei.demo_shoppingcar.utils.MyGridView;
import com.bawei.demo_shoppingcar.utils.NetworkMessage;
import com.google.gson.Gson;
import com.youth.banner.Banner;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.bawei.demo_shoppingcar.application.ContentData.url;


public class MyFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private LinearLayoutManager linearLayoutManagerTop;
    private List<Map<String, Object>> listHader = new ArrayList<Map<String, Object>>();
    private List<ShoppingDataBean.DataBean.DefaultGoodsListBean> defaultGoodsList = new ArrayList<>();
    private List<ShoppingDataBean.DataBean.BestSellersBean.GoodsListBeanX> goodsList = new ArrayList<>();
    private List<ShoppingDataBean.DataBean.Ad1Bean> ad1 = new ArrayList<>();
    private RecyclerView myRecyclerViewTop;
    private RecyclerView myRecyclerViewYouHui;
    private Gson gson;
    private MyGridView myListView;
    private ArrayList<String> list;
    private Banner banner;
    private ImageView img1;
    private ImageView img2;
    private ImageView img3;
    private ImageView img4;
    private TextView text_1;
    private TextView text_2;
    private TextView text_3;
    private TextView text_4;
    private SwipeRefreshLayout swipeRefresh;

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            initData();
            swipeRefresh.setRefreshing(false);
        }
    };
    private LinearLayout linearLayout;

    public MyFragment() {
    }

    public static MyFragment newInstance(String param1, String param2) {
        MyFragment fragment = new MyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        gson = new Gson();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.recy_view, container, false);
        initView(view);
        initData();

        return view;
    }

    private void initData() {

        HomeAsyncTask asyncTask = new HomeAsyncTask(getContext(), new UpdateShopping() {

            private ShoppingDataBean.DataBean data;
            private ShoppingDataBean homeBeanOne;

            @Override
            public void getHaderImageURL(ShoppingDataBean dataBean) {
                if (dataBean==null){
                    Toast.makeText(getContext(),"请先更新在使用",Toast.LENGTH_SHORT).show();
                    return ;
                }
                homeBeanOne = dataBean;
                if (homeBeanOne==null){
                    Toast.makeText(getContext(),"请先更新在使用",Toast.LENGTH_SHORT).show();
                    return  ;
                }

                data = homeBeanOne.getData();

                List<ShoppingDataBean.DataBean.Ad5Bean> ad5 = homeBeanOne.getData().getAd5();
                String image1 = ad5.get(0).getImage();
                String image2 = ad5.get(1).getImage();
                String image3 = ad5.get(2).getImage();
                String image4 = ad5.get(3).getImage();

                String title1 = ad5.get(0).getTitle();
                String title2 = ad5.get(1).getTitle();
                String title3 = ad5.get(2).getTitle();
                String title4 = ad5.get(3).getTitle();

                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(image1,img1,ContentData.options);
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(image2,img2,ContentData.options);
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(image3,img3,ContentData.options);
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(image4,img4,ContentData.options);

                text_1.setText(title1);
                text_2.setText(title2);
                text_3.setText(title3);
                text_4.setText(title4);

                //数组    [ad1]      首页轮播图  Viewpager
                ad1 = data.getAd1();
                //设置图片加载器
                list = new ArrayList<String>();
                Log.d("sss", "1111");
                for (int i = 0; i < ad1.size(); i++) {
                    String image = ad1.get(i).getImage();
                    Log.d("sss", image);
                    list.add(image);
                }
                banner.setImages(list).setImageLoader(new GlideImageLoader()).start();

                List<ShoppingDataBean.DataBean.BestSellersBean> bestSellers = data.getBestSellers();
                ShoppingDataBean.DataBean.BestSellersBean bestSellersBean = bestSellers.get(0);
                //横向滚动列表数据
                goodsList = bestSellersBean.getGoodsList();
                //最后的列表数据
                defaultGoodsList = data.getDefaultGoodsList();


                MyRecyclerAdapterTop myRecyclerAdapterTop = new MyRecyclerAdapterTop(getActivity(), goodsList);
                //TODO   添加监听  ----1
                myRecyclerViewTop.setAdapter(myRecyclerAdapterTop);
                //TODO   添加监听  ----2
                myRecyclerViewYouHui.setAdapter(myRecyclerAdapterTop);

                myRecyclerAdapterTop.setDefaultItemClickListener(new MyRecyclerAdapterTop.MyHomeDefaultItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {

                        String goods_img = goodsList.get(position).getGoods_img();
                        String goods_name = goodsList.get(position).getGoods_name();
                        double shop_price = goodsList.get(position).getShop_price();

                        CommdityBean commdityBean = new CommdityBean(goods_img, goods_name, shop_price);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", commdityBean);
                        Intent intent = new Intent(getActivity(), CommodityActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });


                //默认的商品列表
                myListView.setAdapter(new BaseAdapter() {
                    @Override
                    public int getCount() {
                        return defaultGoodsList.size();
                    }

                    @Override
                    public Object getItem(int position) {
                        return null;
                    }

                    @Override
                    public long getItemId(int position) {
                        return 0;
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_news_recyclerview, parent, false);
                        ImageView goods_image = (ImageView) convertView.findViewById(R.id.goods_image);
                        TextView goods_name = (TextView) convertView.findViewById(R.id.goods_name);
                        TextView goods_shop_price = (TextView) convertView.findViewById(R.id.goods_shop_price);
                        TextView goods_market_price = (TextView) convertView.findViewById(R.id.goods_market_price);
                        goods_market_price.setText(defaultGoodsList.get(position).getMarket_price() + "");
                        goods_shop_price.setText(defaultGoodsList.get(position).getShop_price() + "");
                        goods_name.setText(defaultGoodsList.get(position).getGoods_name() + "");
                        x.image().bind(goods_image, defaultGoodsList.get(position).getGoods_img() + "");
                        return convertView;
                    }
                });
                myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        ShoppingDataBean.DataBean.DefaultGoodsListBean defaultGoodsListBean = defaultGoodsList.get(position);
                        String goods_img = defaultGoodsListBean.getGoods_img();
                        String goods_name = defaultGoodsListBean.getGoods_name();
                        double shop_price = defaultGoodsListBean.getShop_price();
                        CommdityBean commdityBean = new CommdityBean(goods_img, goods_name, shop_price);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", commdityBean);
                        Intent intent = new Intent(getActivity(), CommodityActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);


                    }
                });
            }
        });
        //判断网络状态
        boolean networkAvailable = NetworkMessage.isNetworkAvailable(getContext());
        if (networkAvailable) {
            asyncTask.execute(url);
        } else {
            //dialog网络设置
            AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
            dialog.setTitle("请选择");
            dialog.setMessage("是否立即设置网络?");
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //进入网络设置界面
                    setNetwork(getContext());
                }
            });
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            dialog.show();
        }

    }

    public void initView(View view) {
        banner = (Banner) view.findViewById(R.id.bannerss);
        myListView = (MyGridView) view.findViewById(R.id.myListView);
        myRecyclerViewTop = (RecyclerView) view.findViewById(R.id.myRecyclerViewTop);
        myRecyclerViewYouHui = (RecyclerView) view.findViewById(R.id.myRecyclerViewYouHui);
        //第一个
        linearLayoutManagerTop = new LinearLayoutManager(getActivity());
        linearLayoutManagerTop.setOrientation(LinearLayoutManager.HORIZONTAL);
        myRecyclerViewTop.setLayoutManager(linearLayoutManagerTop);
        //第二个
        LinearLayoutManager linearLayoutManagerHui = new LinearLayoutManager(getActivity());
        linearLayoutManagerHui.setOrientation(linearLayoutManagerHui.HORIZONTAL);
        myRecyclerViewYouHui.setLayoutManager(linearLayoutManagerHui);

        linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);

        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AD5WebViewActivity.class);
                intent.putExtra("url", "http://h.yunifang.com/sign/sign.html?login_check=2");
                startActivity(intent);
            }
        });

        img1 = (ImageView) view.findViewById(R.id.img_1);
        img2 = (ImageView) view.findViewById(R.id.img_2);
        img3 = (ImageView) view.findViewById(R.id.img_3);
        img4 = (ImageView) view.findViewById(R.id.img_4);

        text_1 = (TextView) view.findViewById(R.id.text_1);
        text_2 = (TextView) view.findViewById(R.id.text_2);
        text_3 = (TextView) view.findViewById(R.id.text_3);
        text_4 = (TextView) view.findViewById(R.id.text_4);

        swipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //TODO
                swipeRefresh.setRefreshing(true);
                mHandler.sendEmptyMessageDelayed(1,2000);
            }
        });
    }

    private void setNetwork(Context context) {
        Intent intent = null;
        //判断手机系统的版本  即API大于10 就是3.0或以上版本
        if (android.os.Build.VERSION.SDK_INT > 10) {
            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
        } else {
            intent = new Intent();
            ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
            intent.setComponent(component);
            intent.setAction("android.intent.action.VIEW");
        }
        context.startActivity(intent);
    }

}
